﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Linq;
using System.Text;

namespace HSIA
{
    public class MySms
    {
        public static string CREATE = @"CREATE TABLE [dbo].[Dat_SmsLogs] (
    [KeyId]       INT            IDENTITY (1, 1) NOT NULL,
    [Info]        nvarchar(MAX) NULL,
    [InputDate]   DATETIME       NULL,
    [InputUserId] VARCHAR (40)   NULL,
    [SendDate]    DATETIME       NULL,
    [SendUserId]  VARCHAR (40)   NULL,
    [Phone]       VARCHAR (13)   NULL,
    [Type]        TINYINT        NULL,
    [State]       TINYINT        NULL,
    [Remarks]     NVARCHAR (50)  NULL,
    [Tag]         nvarchar(MAX)  NULL,
    CONSTRAINT [PK_Dat_SmsLogs] PRIMARY KEY CLUSTERED ([KeyId] ASC));";

        public MySms(DatabaseObject dbo)
        {
            this.dbo = dbo;

            //dtSmsData = IsCreate(dbo.sXMLDir);

            dtAccount = dbo.GetDataTableBySql("select * from sys_Account", "Account");
            if (dtAccount == null || dtAccount.Rows.Count == 0) return;

            //Refresh();
        }

        public static MySms Instance { get; set; }

        private DatabaseObject dbo;

        public bool isConnected = false;
        DataTable dtAccount;
        private DataTable dtSmsData;

        private DataTable IsCreate(string strConn)
        {
            DataTable dtSms = dbo.GetDataTableBySql("Select count(*) from Dat_SmsLogs", "SmsLog", strConn);
            if (dtSms == null || dtSms.Columns.Count == 0)
            {
                dbo.ExcuteSQL(CREATE, strConn);
            }
            dtSms = dbo.GetDataTableBySql("Select *,'" + strConn + "' DB_Conn from Dat_SmsLogs where State=1", "SmsLog", strConn);
            return dtSms;
        }

        private void Refresh()
        {
            //dtSmsData.Rows.Clear();
            dtSmsData = IsCreate(dbo.sXMLDir);
            foreach (DataRow drAccount in dtAccount.Rows)
            {
                string sDB_Name = drAccount["DB_Name"].ToString();
                string strConn = string.Format("Data Source={0};Initial Catalog={1};User ID={2};Password={3};",
                    drAccount["IP"], sDB_Name, drAccount["DB_User"], drAccount["DB_Password"]);
                DataTable dt = IsCreate(strConn);
                if (dt != null && dt.Rows.Count > 0) dtSmsData.Merge(dt);
            }
        }

        public DataTable GetData()
        {
            Refresh();
            return dtSmsData;
        }

        public void AddSms(string tel, string msg, string constr)
        {
            if (tel.Length < 11 || string.IsNullOrEmpty(msg)) return;
            DataRow dr = dtSmsData.NewRow();
            dr["Phone"] = tel;
            dr["Info"] = msg;
            dr["InputUserId"] = "admin";
            dr["InputDate"] = DateTime.Now;
            dr["Type"] = 1;
            dr["State"] = (int)SmsLog.StateType.待发;
            //dr["SendUserId"] = msg;

            string sqi = string.Format("Insert Into Dat_SmsLogs(Phone,Info,InputUserId,InputDate,Type,State) values('{0}','{1}','{2}','{3}','{4}','{5}')",
                dr["Phone"], dr["Info"], dr["InputUserId"], dr["InputDate"], dr["Type"], dr["State"]);
            string str = dbo.ExcuteSQL(sqi, constr);
            if (str == "OK") dtSmsData.Rows.Add(dr);
        }

        public void SendSmsState(string keyid, int state, string constr)
        {
            string sqi = string.Format("Update Dat_SmsLogs set State='{1}',SendDate='{2}' Where KeyId='{0}'", keyid, state, DateTime.Now);
            string str = dbo.ExcuteSQL(sqi, constr);

        }

        public static void AddSms(DatabaseObject dbo, string[] info, string msg, string constr)
        {
            if (!string.IsNullOrEmpty(info[0]))
            {
                string[] telList = info[0].Split(';');

                string sqlList = string.Empty;

                foreach (string mobile in telList)
                {
                    if (mobile.Length < 11 || string.IsNullOrEmpty(msg)) continue;

                    //插入数据前检查是否有相同的地点报警
                    string existsSql = string.Format(@"select count(1) nums from Dat_SmsLogs where Phone='{0}' and CharIndex('{1}',Tag)>0 and state=1", mobile, info[1].TrimEnd('-'));

                    DataTable dtWarnInfo = dbo.GetDataTableBySql(existsSql, "WarnList", constr);

                    if (dtWarnInfo != null && dtWarnInfo.Rows.Count > 0)
                    {
                        if (PublicMethod.GetInt(dtWarnInfo.Rows[0]["nums"]) > 0) continue;
                    }

                    //检查同一个电话号码是否不同的地点报警
                    existsSql = string.Format(@"select KeyId,Info,Tag from Dat_SmsLogs where state=1 and Phone='{0}'", mobile);

                    DataTable dtSame = dbo.GetDataTableBySql(existsSql, "SameList", constr);

                    string sql = string.Empty;

                    if (dtSame != null && dtSame.Rows.Count > 0)
                    {
                        int keyId = PublicMethod.GetInt(dtSame.Rows[0]["KeyId"]);
                        string warnInfo = PublicMethod.GetString(dtSame.Rows[0]["Info"]);
                        warnInfo = warnInfo.Replace("【国药物流】", "") + msg;
                        string tag = PublicMethod.GetString(dtSame.Rows[0]["Tag"]);
                        tag = tag + ","+ info[1].TrimEnd('-');

                        sql = string.Format(@"update Dat_SmsLogs set Info='{0}',Tag='{1}' where KeyId={2};", warnInfo, tag, keyId);
                    }
                    else
                    {
                        sql = string.Format("Insert Into Dat_SmsLogs(Phone,Info,InputUserId,InputDate,Type,State,Tag) values('{0}','{1}','{2}','{3}','{4}','{5}','{6}');",
                      mobile, msg, "admin", DateTime.Now, 1, (int)SmsLog.StateType.待发, info[1].TrimEnd('-'));
                    }

                    sqlList += sql;

                }
                //if (tel.Length < 11 || string.IsNullOrEmpty(msg)) return;
                //string sqi = string.Format("Insert Into Dat_SmsLogs(Phone,Info,InputUserId,InputDate,Type,State) values('{0}','{1}','{2}','{3}','{4}','{5}')",
                //   tel, msg, "admin", DateTime.Now, 1, (int)SmsLog.StateType.待发);
                //string str = dbo.ExcuteSQL(sqi, constr);

                if (!string.IsNullOrEmpty(sqlList))
                {
                    string str = dbo.ExcuteSQL(sqlList, constr);
                }
            }
        }
    }
    public class SmsLog
    {
        /// <summary>
        /// 主键
        /// </summary>
        [Description("主键")]
        public string KeyId { get; set; }
        /// <summary>
        /// 信息
        /// </summary>
        [Description("信息")]
        public string Info { get; set; }

        [Description("时间")]
        public DateTime InputDate { get; set; }

        [Description("用户名")]
        public string InputUserId { get; set; }

        [Description("时间")]
        public DateTime SendDate { get; set; }

        [Description("用户名")]
        public string SendUserId { get; set; }

        [Description("电话")]
        public string Phone { get; set; }

        [Description("类型")]
        public byte Type { get; set; }

        [Description("发送状态")]
        public byte State { get; set; }

        [Description("备注")]
        public string Remarks { get; set; }

        public enum StateType
        {
            完成 = 0,
            待发 = 1,
            执行 = 2,
            错误 = 3,
            取消 = 4,
        }
    }
}
